import {
  getLarkAuth,
  getAccessToken,
  isLarkLogin
} from '#utils/lark/larkUtils.js';
import { getWikiSheet } from './getDocument.js';
import formatDocList from '#utils/saveMultilingual.js';
import { delay } from '#utils/index.js';

// 飞书文档拉取
const getDoc = async (ctx, next) => {
  if (await isLarkLogin(ctx)) {
    const { file_name } = ctx.query;
    const doc = await getWikiSheet(ctx, ctx.params.all);
    if (doc) {
      const json = await formatDocList(doc);
      await delay(1000);
      ctx.set('Content-Type', 'application/json');
      ctx.set(
        'Content-Disposition',
        `attachment; filename="${file_name || 'formatData'}.json"`
      );
      ctx.body = JSON.stringify(json); // 格式化 JSON 数据
    }
  } else {
    const authUrl = await getLarkAuth();
    ctx.session.getDocUrl = `getDoc/${ctx.params.all}`;
    ctx.type = 'html';
    ctx.body = `
    <div style="width: 100%;height: 100%;text-align: center;padding-top: 20px;box-sizing: border-box">
        前往登录飞书授权: <a href="${authUrl}">Check</a>
    </div>
    `;
  }
};

// 飞书授权回调
const callBack = async (ctx, next) => {
  const code = ctx.query.code;
  if (!code) {
    ctx.fail('1009', 'code 不存在');
  }
  try {
    const larkAuth = await getAccessToken(code, ctx);
    ctx.session.larkAuth = larkAuth;
    const targetUrl = ctx.session.getDocUrl;
    ctx.type = 'html';
    ctx.body = `
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Redirecting...</title>
            <script>
                setTimeout(function() {
                    window.location.href = "${targetUrl}";
                }, 1000);
            </script>
        </head>
            <div style="width: 100%;height: 100%;text-align: center;padding-top: 20px;box-sizing: border-box">
                down file, loading...
            </div>
        </body>
    </html>
    `;
  } catch (error) {
    ctx.fail('1009', '授权失败');
  }
};

export default {
  'GET&/lark/getDoc/:all': getDoc,
  'GET&/lark/callBack': callBack
};
